package com.ken.apollo.config.interceptor;

import com.ken.apollo.domain.vo.AdminUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

/**
 * 登录检查拦截器
 * 拦截需要登录才能访问的后台页面
 *
 * @author Ken
 * @since 2025-08-25
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.debug("登录检查拦截器 - 请求URI: {}", requestURI);

        // 获取Session
        HttpSession session = request.getSession(false);
        if (session == null) {
            log.info("Session不存在，重定向到登录页面 - URI: {}", requestURI);
            redirectToLogin(request, response);
            return false;
        }

        // 检查是否已登录
        AdminUserVo adminUser = (AdminUserVo) session.getAttribute("admin_user");
        if (adminUser == null) {
            log.info("用户未登录，重定向到登录页面 - URI: {}", requestURI);
            redirectToLogin(request, response);
            return false;
        }

        // 检查用户状态
        if (adminUser.getStatus() == null || !adminUser.getStatus()) {
            log.warn("用户账号已被禁用，重定向到登录页面 - 用户: {}", adminUser.getUsername());
            session.invalidate();
            redirectToLogin(request, response);
            return false;
        }

        log.debug("用户已登录，允许访问 - 用户: {}, URI: {}", adminUser.getUsername(), requestURI);
        return true;
    }

    /**
     * 重定向到登录页面
     */
    private void redirectToLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String requestURI = request.getRequestURI();
        
        // 如果是AJAX请求，返回JSON响应
        if (isAjaxRequest(request)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未登录或登录已过期\",\"data\":null}");
            return;
        }

        // 普通请求重定向到登录页面
        String loginUrl = "/admin/login";
        
        // 保存原始请求URL，登录后可以跳转回来
        if (!requestURI.equals(loginUrl) && !requestURI.equals("/admin/login")) {
            request.getSession(true).setAttribute("redirect_url", requestURI);
        }
        
        response.sendRedirect(loginUrl);
    }

    /**
     * 判断是否为AJAX请求
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("X-Requested-With");
        String contentType = request.getHeader("Content-Type");
        String accept = request.getHeader("Accept");
        
        return "XMLHttpRequest".equals(requestedWith) ||
               (contentType != null && contentType.contains("application/json")) ||
               (accept != null && accept.contains("application/json"));
    }
}